const SysAuthType = appRequire('model/desktop/SysAuthType');
const PageResultVo = appRequire('vo/PageResultVo.js');
class SysAuthTypeSequelizeDao {
  constructor() {

  }
  static async create() {
    await SysAuthType.sync();
  }
  static async saveOne(authType) {
    try {
      await SysAuthType.create(authType);
    } catch (error) {
      throw new Error(error);
    }
  }
  static async updateOne(authType) {
    try {
      await SysAuthType.update(authType,{where:{id:authType.id}});
    } catch (error) {
      throw new Error(error);
    } 
  }
  static async deleteById(id) {
    try {
      await SysAuthType.destroy({where:{id}});
    } catch (error) {
      throw new Error(error);
    }
  }
  static async deleteMany(ids) {
    try {
      ids = ids.split(",");
      console.log(ids);
      await SysAuthType.destroy({where:{id:ids}});
    } catch (error) {
      throw new Error(error);
    }
  }
  /**
   * 定制化查找字段
   * @param {*} id 
   */
  static async findOne(id) {
    try {
      let data = await SysAuthType.findOne({
        where:{
          id
        },
        raw:true,
        attributes: {exclude:[]},
      });
      return data;
    } catch (error) {
      throw new Error(error);
    } 
  }
  static async findById(id) {
    try {
      let data = await SysAuthType.findOne({
        where:{
          id
        },
        raw:true,
        attributes: { exclude: [] },
      });
      return data;
    } catch (error) {
      throw new Error(error);
    } 
  }
  static async findAllByType(type) {
    // console.log(type);
    let types = type.type;
    try {
      let data = await SysAuthType.findAll({
        where:{
          type:{
            [Op.eq]:type.type
          }
        },
        raw:true,
        attributes: ["id",["type_name","name"],"type","sort"],
      });
      return data;
    } catch (error) {
      throw new Error(error);
    }
  }
  static async findAll() {
    try {
      let data = await SysAuthType.findAll({
        raw:true,
        attributes: { exclude: [] },
      });
      return data;
    } catch (error) {
      throw new Error(error);
    } 
  }
  static async findByPage(page) {
    try {
      let offset = (page.pageNum-1)*page.pageSize;
      let limit = page.pageSize;
      let where = {};
      //动态拼装sql的where条件
      if(page.searchParams&&page.searchParams.typeName){
        where.type_name = {
          [Op.like]: `%${page.searchParams.typeName}%`,
        }
      }
      let result = await SysAuthType.findAndCountAll({
        where,offset,limit,raw:true,attributes:{exclude:[]},order:[["create_time","DESC"]]
      })
      console.log(result)
       return PageResultVo.success('success',result.count,result.rows);
    } catch (error) {
      throw new Error(error);
    }
  } 
}
module.exports = SysAuthTypeSequelizeDao;